package com.CommunityHub.kiana.controller;


import com.CommunityHub.kiana.po.MemberDetail;
import com.CommunityHub.kiana.po.User;
import com.CommunityHub.kiana.service.MemberService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/UpdateProfileServlet")
public class UpdateProfileServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        User user = (User) session.getAttribute("user");
        int memberId = user.getId();

        // 获取表单参数
        String realName = request.getParameter("realName");
        String sex = request.getParameter("gender");
        String phone = request.getParameter("phone");
        String idCard = request.getParameter("idCard");
        String contactName = request.getParameter("contactName");
        String contactPhone = request.getParameter("contactPhone");

        MemberService memberService = new MemberService();
        try {
            // 获取会员信息
            MemberDetail member = memberService.getMemberDetail(memberId);

            // 更新信息
            member.setRealName(realName);
            member.setGender(sex);
            member.setPhone(phone);
            member.setIdCard(idCard);
            member.setContactName(contactName);
            member.setContactPhone(contactPhone);

            // 保存更新
            boolean success = memberService.updateMemberInfo(member);
            if (success) {
                // 重新加载完整信息
                MemberService.CompleteMemberInfo info =
                        memberService.getCompleteMemberInfo(memberId);
                session.setAttribute("memberInfo", info);

                response.sendRedirect("viewProfile.jsp");
            } else {
                request.setAttribute("error", "更新个人信息失败");
                request.getRequestDispatcher("editProfile.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            request.setAttribute("error", "系统错误: " + e.getMessage());
            request.getRequestDispatcher("editProfile.jsp").forward(request, response);
        }
    }
}
